<template>
  <section class="components work-seater">

    <a>
      <i class="el-icon-headset icon-style" @click="phoneClick"></i>
    </a>

    <!-- 如果已登录 -->
    <template v-if="loginStatus">
      <div class="status">
        <el-dropdown @command="statusChange" trigger="click" style="padding-left: 10px;">
          <i class="el-icon-service icon-style"></i>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :disabled="currentStatus === 'READY'" command="free">置闲</el-dropdown-item>
            <el-dropdown-item :disabled="currentStatus === 'BUSY'" command="busy">置忙</el-dropdown-item>
            <!-- <el-dropdown-item :disabled="currentStatus === 'AWAY'" command="break">小休</el-dropdown-item> -->

            <el-dropdown-item :disabled="awayStatus === item.text" v-for="(item, index) in awayStatusList" :key="index" :command="item.value">
              {{ item.text }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span class="status-desc">{{awayStatus|| statusMap(currentStatus)}}</span>
      </div>

      <i class="el-icon-phone icon-style" style="padding-left: 10px;" @click="onClick"></i>
    </template>

    <!-- <div v-if="cPhoneStatus==='offline' && !loginStatus" class="error-tip">Cphone登录失败,请重启Cphone后重新登录</div> -->

    <div id="content"></div>

    <el-dialog ref="dialog" width="800px" id="work-seater-dialog" :visible="isShowModal" @close="hideModal" :close-on-click-modal="false" show-close title="呼叫中心坐席控制台">
      <seat-setting :visible="isShowModal" @initWebAgent="initWebAgent" @onCancel="hideModal" ref="wechat" @logout="logout" />
    </el-dialog>

  </section>
</template>

<script lang="ts">
import { Vue, Component, Watch, } from "vue-property-decorator";
import SeatSetting from "~/components/call-center/seat-setting.vue";
// import CallCenterService from "~/utils/call-center/call-socket.service";
import { StorageService } from "~/utils/storage.service";
import { addDragListener, mountWebAgent } from "~/components/call-center/util";
import { namespace } from "vuex-class";
import { callState } from '~/utils/call-center/state';

const callCenterStore = namespace("call-center");

@Component({
  components: {
    SeatSetting,
    // SeatSetup
  },
})
export default class WorkSeater extends Vue {
  @callCenterStore.Mutation private updateLogin: (status: boolean) => void;
  @callCenterStore.Mutation private updateCurrentStatus: (status: string) => void;
  @callCenterStore.Mutation private updateEventData: (data: any) => void;
  @callCenterStore.Mutation private setMultiChannelLogout: (data: any) => void;
  @callCenterStore.Mutation private setAwayStatusList: (data: any) => void;
  @callCenterStore.Mutation private setIsShowModal: (data: boolean) => void;

  @callCenterStore.State private loginStatus!: boolean;
  @callCenterStore.State private currentStatus!: string;
  @callCenterStore.State private eventData!: any;
  @callCenterStore.State private cPhoneStatus: string
  @callCenterStore.State private awayStatusList: any
  @callCenterStore.State private isShowModal: any

  @callCenterStore.State private multiChannelLogout: () => void

  private currentMsg: any = null

  private awayStatus: string = ''


  // private awayStatusList: any[] = []

  private webAgent: any = {}

  @Watch('currentStatus')
  private currentStatusChange (v) {
    console.log('currentStatus', v);
    console.log('888currentStatus', this.currentStatus);

  }

  private onOffline () {
    console.log('网络断开连接');
    this.$message.error('Cphone断开连接,请重新登录');
    this.logout()
  }


  /**
   * mounted
   */
  private mounted () {
    this.$store.dispatch("call-center/reSet");
    // CallCenterService.initSocket();
    // CallCenterService.onDisConnect().subscribe((x) => {
    //   this.$store.dispatch("call-center/reSet");
    //   this.$message.error("呼叫中心连接中断");
    // });

    // 自动登录
    const params = sessionStorage.getItem('webAgentLoginParmas')
    if (params) {
      this.initWebAgent(JSON.parse(params))
    }
    this.currentMsg = null
    this.setIsShowModal(false)
    // this.isShowModal = false

    
    this.drag()

    // 监听断网事件
    window.addEventListener('offline', this.onOffline)


  }

  private drag () {
    setTimeout(() => {
      addDragListener(document.querySelector('.cchat-header'))
    }, 2000);

  }

  private updateLoginState (login) {
    callState.updateLoginState(login)
    this.updateLogin(login)
  }


  private getAwayStatusList (status: string) {
    const splitList = status.split(';').filter(v => v)
    const list = splitList.map(v => {
      const [text, value] = v.split('=')
      const obj = {
        text, value
      }
      return obj
    })

    return list
  }

  private initWebAgent (params) {
    if (callState.isLogined) {
      this.updateLogin(true)
      return
    }
    const dialog = this.$refs.dialog as any
    mountWebAgent(params, (data) => {
      console.log('data', data);
      console.log('data.status', data.status);
      this.webAgent = data.WebAgent
      this.setMultiChannelLogout(data.WebAgent.multiChannelLogout)

      if (data.status === 'loginSuccess') {
        // data.WebAgent.WaChat.show()
        // this.updateLogin(true)
        this.updateLoginState(true)
        sessionStorage.setItem('webAgentLoginParmas', JSON.stringify(params))
        console.log('currentMsg', this.currentMsg);
        if (!this.currentMsg) {
          const msg = this.$message.success('坐席登录成功')
          this.currentMsg = msg
        }
        this.$nextTick(() => {
          // this.isShowModal = false
           this.setIsShowModal(false)
          if (data.awayStatusList) {
            this.setAwayStatusList(this.getAwayStatusList(data.awayStatusList))
          }
        })
        this.initIntelSelect()
        this.drag()
      } else {
        console.log('currentMsg', this.currentMsg);
        if (!this.currentMsg) {
          const msg = this.$message.error('坐席登录失败：' + data.msg)
          this.currentMsg = msg
        }
  
        // this.isShowModal = false
        this.setIsShowModal(false)

        sessionStorage.removeItem('webAgentLoginParmas')
        data.WebAgent.WaChat.hide()
        this.updateCurrentStatus('')
        this.updateLoginState(false)

      }

      console.log('end=>this.isShowModal', this.isShowModal);

    })
  }

  private statusMap (status: string) {
    const map = {
      WORKING: '工作中',
      BUSY: '置忙',
      READY: '置闲',
      AWAY: '小休',
    }
    return map[status]
  }

  private statusChange (status) {
    console.log('eventData', this.eventData, this.webAgent.multiChannelState);
    if (!this.webAgent.multiChannelState) {
      return
    }
    this.awayStatus = ''
    if (status === 'free') {
      this.webAgent.multiChannelState.agentReady(() => {
        console.log('[CDesk] 多渠道能力置闲成功');
      }, (e) => {
        console.log('[CDesk] 多渠道能力置闲失败', e);
      });
    } else if (status === 'busy') {
      this.webAgent.multiChannelState.agentBusy(() => {
        console.log('[CDesk] 多渠道能力置忙成功');
      }, function () {
        console.log('[CDesk] 多渠道能力置忙失败');
      });
    } else {
      this.awayStatus = this.awayStatusList.find(v => v.value === status)?.text
      // const { autoStatus } = this.eventData.ext || {}
      console.log('status', status);
      this.webAgent.multiChannelState.agentAway(() => {
        console.log('[CDesk] 多渠道能力小休成功');
      }, function () {
        console.log('[CDesk] 多渠道能力小休失败');
      }, Number(status));
    }

  }

  private phoneClick () {
    // this.isShowModal = true
    this.setIsShowModal(true)
    this.currentMsg = null
  }

  private hideWachat () {
    (window as any).WebAgent.WaChat?.hide()
  }

  private hideModal(){
    this.setIsShowModal(false)
  }

  //设置电话条默认选择智能外显
  private initIntelSelect () {
    const ele = document.querySelector('#intelSelect') as HTMLInputElement
    if (ele) {
      ele.checked = true
    }
  }

  private onClick () {
    // if (this.webAgent.WaChat) {
    //   this.webAgent.WaChat.toggle()
    // }

    (window as any).WebAgent.WaChat?.toggle()
  }

  private logout (clearCache = true) {
    console.log('logout', this.webAgent);
    // 如果正在打电话则不允许登出
    if (callState.calling){
      this.$message.warning('请先挂断电话再执行登出操作')
      return
    }

    if (clearCache) sessionStorage.removeItem('webAgentLoginParmas')
    this.updateLoginState(false)

    this.hideWachat()
    this.multiChannelLogout()
    this.updateEventData({})
    this.updateCurrentStatus('')
    this.currentMsg = null
    // this.isShowModal = false
    this.setIsShowModal(false)
    this.webAgent?.vm?.callNumber(undefined);
    this.awayStatus=''

  }

  private destroyed () {
    this.hideWachat()
    this.logout(false)
    window.removeEventListener('offline', this.onOffline)
  }
}
</script>

<style lang="less">
.components.work-seater {
  padding-top: 8px;
  margin-right: 10px;
  display: flex;

  .icon-style {
    font-size: 25px;
    font-weight: bold;
    color: #0064bf;
  }
}

.row {
  margin: 0 !important;
}

.row:after,
.row:before {
  display: flex !important;
  content: none !important;
}

.status-desc {
  position: relative;
  bottom: 3px;
  left: 2px;
}

.error-tip {
  background-color: #b1afb1;
  border-radius: 15px;
  max-width: 185px;
  color: #fff;
  padding: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-left: 8px;
}
</style>